import string
import main
import scanlinux
import os.path
import pygtk
pygtk.require("2.0")
import gtk
import os, stat
from decimal import *

builder = gtk.Builder()
store = gtk.TreeStore(str, gtk.gdk.Pixbuf, str, str, bool)
store2 = gtk.TreeStore(str, gtk.gdk.Pixbuf, str, str, bool)
port_store = gtk.TreeStore(gtk.gdk.Pixbuf, str)
frec_store = gtk.TreeStore(gtk.gdk.Pixbuf, str)

port_list = scanlinux.scan();

def dirwalk(path, parent=None):
    
    for f in os.listdir(path):
        fullname = os.path.join(path, f)
        # Extract metadata from the item
        fdata = os.stat(fullname)
        # Determine if the item is a folder
        is_folder = stat.S_ISDIR(fdata.st_mode)
        file_type = os.path.splitext(fullname)[-1]
        # Generate an icon from the default icon theme
        if is_folder:
            file_image_name = "folder-music"
        else:
            if (file_type == '.mp3')|(file_type == '.wav'):
                file_image_name = "sound"
            else:
                file_image_name = "document"
        img = gtk.icon_theme_get_default().load_icon(file_image_name,32, 0)
        # Append the item to the TreeStore
        float_size = (fdata.st_size * 1.0) / 1000;
        str_size = '%0.2f KB'% float_size
        getcontext().prec = 2;
        li = store.append(parent, [f, img, fullname, str_size, is_folder])
        # If the item is a folder, descend into it
        if is_folder: dirwalk(fullname, li)

#a partir de este path se navega
dirwalk("/home/martin/Desktop/Digital")

class Gui(object):
    def __init__(self):
        
        builder.add_from_file("gui.xml")
        builder.connect_signals({ "gtk_main_quit" : gtk.main_quit,
                                    "on_import_clicked" : self.on_import_clicked,
                                    "on_delete_clicked" : self.on_delete_clicked,
                                    "on_frecuency_chooser_changed" : self.on_frecuency_chooser_changed,
                                    "on_port_chooser_changed" : self.on_port_chooser_changed,
                                    "on_sd_clicked" : self.on_sd_clicked,
                                    "on_import_menu_activate" : self.on_import_menu_activate,
                                    })

        self.set_images()
        self.set_port_chooser()
        self.set_frecuency_chooser()

        col = gtk.TreeViewColumn("File")
        # Create a column cell to display text
        col_cell_text = gtk.CellRendererText()
        # Create a column cell to display an image
        col_cell_img = gtk.CellRendererPixbuf()
        # Add the cells to the column
        col.pack_start(col_cell_img, False)
        col.pack_start(col_cell_text, True)
        # Bind the text cell to column 0 of the tree's model
        col.add_attribute(col_cell_text, "text", 0)
        # Bind the image cell to column 1 of the tree's model
        col.add_attribute(col_cell_img, "pixbuf", 1)
        col.set_min_width(185)

        col2 = gtk.TreeViewColumn("Size")
        col2_cell_text = gtk.CellRendererText()
        col2.pack_start(col2_cell_text)
        col2.add_attribute(col2_cell_text, "text", 3)

        col3 = gtk.TreeViewColumn("File")
        # Create a column cell to display text
        col3_cell_text = gtk.CellRendererText()
        # Create a column cell to display an image
        col3_cell_img = gtk.CellRendererPixbuf()
        # Add the cells to the column
        col3.pack_start(col_cell_img, False)
        col3.pack_start(col_cell_text, True)
        # Bind the text cell to column 0 of the tree's model
        col3.add_attribute(col_cell_text, "text", 0)
        # Bind the image cell to column 1 of the tree's model
        col3.add_attribute(col_cell_img, "pixbuf", 1)
        col3.set_min_width(185)

        col4 = gtk.TreeViewColumn("Size")
        col4_cell_text = gtk.CellRendererText()
        col4.pack_start(col2_cell_text)
        col4.add_attribute(col2_cell_text, "text", 3)
	
	# Create the ProgressBar
        #self.pbar = gtk.ProgressBar()
        #self.pbar.show()

        self.filesystem_tree = builder.get_object("filesystem_tree")
        self.filesystem_tree.set_model(store)
        self.filesystem_tree.append_column(col)
        self.filesystem_tree.append_column(col2)
        
        self.ipod_list = builder.get_object("ipod_list")
        self.ipod_list.set_model(store2)
        self.ipod_list.append_column(col3)
        self.ipod_list.append_column(col4)

    def set_images(self):
        self.import_button = builder.get_object("import")
        self.img_import_button = gtk.image_new_from_pixbuf(gtk.icon_theme_get_default().load_icon("music-player",48, 0))
        self.import_button.set_image(self.img_import_button)

        self.delete_button = builder.get_object("delete")
        self.img_delete_button = gtk.image_new_from_pixbuf(gtk.icon_theme_get_default().load_icon("edit-delete",48, 0))
        self.delete_button.set_image(self.img_delete_button)

        self.sd_button = builder.get_object("sd")
        self.img_sd_button = gtk.image_new_from_pixbuf(gtk.icon_theme_get_default().load_icon("media-memory-sd",28, 0))
        self.sd_button.set_image(self.img_sd_button)

    def set_port_chooser(self):
        for name in port_list:
            combo_img = gtk.icon_theme_get_default().load_icon("drive-harddisk-usb",16, 0)
            combo_str = name
            port_store.append(None, [combo_img, combo_str])
        col1_combobox_text = gtk.CellRendererText()
        col1_combobox_img = gtk.CellRendererPixbuf()
        self.port_chooser = builder.get_object("port_chooser")
        self.port_chooser.set_model(port_store)
        self.port_chooser.pack_start(col1_combobox_img, False)
        self.port_chooser.pack_start(col1_combobox_text, True)
        self.port_chooser.add_attribute(col1_combobox_text, "text", 1)
        self.port_chooser.add_attribute(col1_combobox_img, "pixbuf", 0)


    def set_frecuency_chooser(self):
        frecuency_list = [1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200]
        for rate in frecuency_list:
            frec_combo_img = gtk.icon_theme_get_default().load_icon("utilities-system-monitor",16, 0)
            frec_combo_str = rate
            frec_store.append(None, [frec_combo_img, frec_combo_str])
        col1_frec_combobox_text = gtk.CellRendererText()
        col1_frec_combobox_img = gtk.CellRendererPixbuf()
        self.frecuency_chooser = builder.get_object("frecuency_chooser")
        self.frecuency_chooser.set_model(frec_store)
        self.frecuency_chooser.pack_start(col1_frec_combobox_img, False)
        self.frecuency_chooser.pack_start(col1_frec_combobox_text, True)
        self.frecuency_chooser.add_attribute(col1_frec_combobox_text, "text", 1)
        self.frecuency_chooser.add_attribute(col1_frec_combobox_img, "pixbuf", 0)

    def on_import_clicked(self, widget):
        iter = self.filesystem_tree.get_selection().get_selected()[1]
        if iter != None:
            f = self.filesystem_tree.get_model().get_value(iter, 0)
            if string.find(f, ".wav") != -1:
                fullname = self.filesystem_tree.get_model().get_value(self.filesystem_tree.get_selection().get_selected()[1], 2)
                # Extract metadata from the item
                fdata = os.stat(fullname)
                # Determine if the item is a folder
                is_folder = stat.S_ISDIR(fdata.st_mode)
                file_type = os.path.splitext(fullname)[-1]
                # Generate an icon from the default icon theme
                if is_folder:
                    file_image_name = "folder-music"
                else:
                    if (file_type == '.mp3' or file_type == '.wav'):
                        file_image_name = "sound"
                    else:
                        file_image_name = "document"
                float_size = (fdata.st_size * 1.0) / 1000;
                str_size = '%0.2f KB' % float_size
                img = gtk.icon_theme_get_default().load_icon(file_image_name,32, 0)
                # Append the item to the TreeStore
                store2.append(None, [f, img, fullname, str_size, is_folder])
                main.convertir_a_headerless_y_transmitir(fullname)
            else:
                print "wrong type of file"

    def on_delete_clicked(self, widget):
        store2.remove(self.ipod_list.get_selection().get_selected()[1])

    def on_frecuency_chooser_changed(self, widget):
        main.cambiar_frecuencia(self.frecuency_chooser.get_model().get_value(self.frecuency_chooser.get_active_iter(),1))

    def on_port_chooser_changed(self, widget):
        main.cambiar_puerto(self.port_chooser.get_model().get_value(self.port_chooser.get_active_iter(),1))

    def on_sd_clicked(self, widget):
            main.inicializar_memoria()
            print "se debe inicializar la sd"

    def on_import_menu_activate(self, widget):
        print "noda aun"
Gui()
gtk.main()
